/*
 *  Copyright (C) 2010 Martin Haulrich <mwh.isv@cbs.dk> and Matthias Buch-Kromann <mbk.isv@cbs.dk>
 *
 *  This file is part of the IncrementalParser package.
 *
 *  The IncrementalParser program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.osdtsystem.incparser.learners;

import org.osdtsystem.incparser.features.WeightVectorDense;
import org.osdtsystem.incparser.features.WeightVector;
import org.osdtsystem.incparser.features.FeatureVector;

/**
 * 'upd' argument in update method should be:
 *    number of iteration * number of instances - (number of instances * (current iteration - 1) + (current instance + 1) + 1)
 *
 * @author Martin Haulrich
 */
public class PerceptronLearner implements Learner {
    WeightVector weights;
    WeightVector sumWeights;
    int updates;
    final boolean average;

    public PerceptronLearner(int paramSize) {
        this(paramSize, true);
    }

    public PerceptronLearner(int paramSize, boolean average) {
        this.average = average;
        weights = new WeightVectorDense(paramSize);
        sumWeights = new WeightVectorDense(paramSize);
        updates = 0;
    }

    @Override
    public WeightVector weights() {
        return weights;
    }

    @Override
    public void averageWeights() {
        weights.clear();
        sumWeights.addTo(1f / updates, weights);
    }

    @Override
    public void update(FeatureVector goldVector, FeatureVector systemVector, 
            double loss, double upd) {
        updates++;

        if (loss <= 0)
            return;

        FeatureVector distVector = goldVector.subtract(systemVector);
        distVector.addTo(1, weights);
        distVector.addTo((float) upd, sumWeights);
    }
}
